/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.lang.Nullable;

/**
 * Delegate for AbstractApplicationContext's post-processor handling.
 *
 * @author Juergen Hoeller
 * @since 4.0
 */
final class PostProcessorRegistrationDelegate {

	private PostProcessorRegistrationDelegate() {
	}


	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		// 1.用来存储已经执行完了的BeanFactoryPostProcessor
		Set<String> processedBeans = new HashSet<>();

		// 2.满足条件, 进入
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			// 3.regularPostProcessors用于存放普通的 BeanFactoryPostProcessor, 一般为空
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			// 4.registryProcessors 用来存放BeanDefinitionRegistryPostProcessor,
			// BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子接口
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
			// 5.这里 beanFactoryPostProcessors.size == 0, 这里跳过
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					regularPostProcessors.add(postProcessor);
				}
			}

			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			// 翻译: 在这里不会初始化普通的bean对象, 让它们处于未初始化的状态,  我们需要先让bean factory post processors来处理它们,
			// 其次, 需要分离出来 PriorityOrdered(实现优先级顺序的), Ordered(普通顺序的)和一般的BeanDefinitionRegistryPostProcessors
			// 6. 临时列表
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			// 翻译: 先处理实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessors
			// 7.获取BeanDefinitionRegistryPostProcessor的实现类的名称, 从beanDefinitionNames中获取的, 结果为:
			// internalConfigurationAnnotationProcessor, 对应的BeanDefinition为: ConfigurationClassPostProcessor对应的BeanDefinition
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			// 8.遍历所有的 BeanDefinitionRegistryPostProcessor, 找到实现PriorityOrdered优先级接口的
			for (String ppName : postProcessorNames) {
				// 9.这里只有一个: ConfigurationClassPostProcessor
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					// 10.beanFactory#getBean(beanName, beanClass), 实例化并初始化beanClass对象
					// 添加到currentRegistryProcessors中
					// 在这里完成了核心bean ConfigurationClassPostProcessor 的实例化和初始化
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					// 把name放到processedBeans，后续会根据这个集合来判断处理器是否已经被执行过了
					processedBeans.add(ppName);
				}
			}
			// 11.按优先级排序 BeanDefinitionRegistryPostProcessor 的实现bean
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// 12.合并Processors，为什么要合并，因为registryProcessors是装载BeanDefinitionRegistryPostProcessor的
			// 一开始的时候，spring只会执行BeanDefinitionRegistryPostProcessor独有的方法
			// 而不会执行BeanDefinitionRegistryPostProcessor父类的方法，即BeanFactoryProcessor的方法
			// 所以这里需要把处理器放入一个集合中，后续统一执行父类的方法
			// 这里目前还只有一个 ConfigurationClassPostProcessor
			registryProcessors.addAll(currentRegistryProcessors);
			// 13.这里调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessors的
			// postProcessBeanDefinitionRegistry()方法
			// 目前只有一个: ConfigurationClassPostProcessor
			// 这里需要解析核心类 ConfigurationClassPostProcessor, 它用来完成bean的扫描并创建BeanDefinition, 注册到beanDefinitionMap中
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			// 14.跟上述过程一样, 这里处理实现Ordered接口的 BeanDefinitionRegistryPostProcessor, 实例化初始化后
			// 执行其postProcessBeanDefinitionRegistry()方法
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			// 15.跟上述过程一样, 处理未实现PriorityOrdered和Ordered接口的普通的 BeanDefinitionRegistryPostProcessor
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName);
						reiterate = true;
					}
				}
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
				currentRegistryProcessors.clear();
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			// 16. BeanDefinitionRegistryPostProcessor接口的实现类调用其父接口【BeanFactoryPostProcessor】
			// 的方法【postProcessBeanFactory】!!!
			// 这里需要看核心类: ConfigurationClassPostProcessor
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			// 17.调用普通 【BeanFactoryPostProcessor】接口实现类的方法【postProcessBeanFactory】!!!
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			// Invoke factory processors registered with the context instance.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		//【总结】以上先后初始化并实例化实现了PriorityOrdered接口、Ordered接口、和普通的BeanDefinitionRegistryPostProcessor的实现类, 并添加到BeanFactory一级缓存中
		// 先后调用其 postProcessorBeanDefinitionRegistry
		// 之后, 再先后调用其postProcessBeanFactory方法

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		// 18.获取BeanFactoryPostProcessor对应的实现类的名称, 从beanDefinitionNames中获取的,
		// 结果为:internalConfigurationAnnotationProcessor, internalEventListenerProcessor两个name,
		// 对应的BeanDefinition为:ConfigurationClassPostProcessor对应的BeanDefinition, 以及EventListenerMethodProcessor对应的BeanDefinition
		// 【注意】如果此时我们有自定义的BeanFactoryPostProcessor, 且注册到容器中, 执行到这里的时候
		// 我们自定义的BeanFactoryPostProcessor,已经被前面的内置的实现PriorityOrdered接口的
		// BeanDefinitionRegistryPostProcessor--【ConfigurationClassPostProcessor】封装成BeanDefinition并注册到beanDefinitionMap中了
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		// 19.将获取的BeanFactoryPostProcessor进行分类, 按照PriorityOrdered、Ordered以及未排序三个维度
		// 【注意】我们自定义的BeanFactoryPostProcessor将在这里被初始化完成, 并调用其postProcessBeanFactory
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			}
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// 20.先后调用普通【BeanFactoryPostProcessor】的 【postProcessBeanFactory】方法
		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		beanFactory.clearMetadataCache();
	}

	public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
		// BeanPostProcessor的来源主要有三个:
		// 第一种:
		// 		spring内置的(有2个): 调用AnnotationConfigApplicationContext#this()方法就会添加到bdMap中, 但还没有添加到BeanFactory的beanPostProcessors属性中
		// 		包括: internalAutowiredAnnotationProcessor, internalCommonAnnotationProcessor 这两个是在
		// 第二种:
		//      在调用ConfigurationClassPostProcessor#postProcessBeanFactory()方法中, 没有注册到bdMap中, 但已经添加到BeanFactory的beanPostProcessors属性中
		//      ApplicationContextAwareProcessor, ApplicationListenerDetector, ImportAwareBeanPostProcessor
		// 第三种:
	 	//		自定义的BeanPostProcessor: 在@5 扫描的时候会被封装成bd, 并注册到bdMap中, 此时没有添加到BeanFactory的beanPostProcessors属性中

		// 1.从bdNames中获取BeanPostProcessor对应的beanName, 这里可以获取到上述的第一种和第三种
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		// Register BeanPostProcessorChecker that logs an info message when
		// a bean is created during BeanPostProcessor instantiation, i.e. when
		// a bean is not eligible for getting processed by all BeanPostProcessors.
		// 2.计算BeanPostProcessor总数:
		// beanFactory.getBeanPostProcessorCount() --> 上述第二种的数量
		// postProcessorNames --> 上述第一种和第三种的数量
		// 1 --> 新增的BeanPostProcessorChecker
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		// 3.根据PriorityOrdered, Ordered, 未实现排序的分开处理
		// 3.1 实现PriorityOrdered的BeanPostProcessor
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		// 3.2 实现PriorityOrdered同时实现MergedBeanDefinitionPostProcessor的BeanPostProcessor
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		// 3.3 实现Ordered的BeanPostProcessor
		List<String> orderedPostProcessorNames = new ArrayList<>();
		// 3.4  未实现排序的BeanPostProcessor
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();

		// 4.从第一种和第三种里面找, 实例化并初始化完成后, 分别添加到对应的列表中
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				// 【重点】在这里完成实现PriorityOrdered接口的BeanPostProcessor的实例化和初始化
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		// 5.排序实现了PriorityOrdered的
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		// 6.添加到BeanFactory的beanPostProcessors属性中
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
		for (String ppName : orderedPostProcessorNames) {
			// 【重点】在这里完成实现Ordered接口的BeanPostProcessor的实例化和初始化
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		// 7.排序实现了Ordered的
		sortPostProcessors(orderedPostProcessors, beanFactory);
		// 8.添加到BeanFactory的beanPostProcessors属性中
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
		for (String ppName : nonOrderedPostProcessorNames) {
			// 【重点】在这里完成普通的BeanPostProcessor的实例化和初始化
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		// 9.添加到BeanFactory的beanPostProcessors属性中
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		// 10.排序internalPostProcessors, 并重新添加进去, 到尾部
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		// 11.重新添加ApplicationListenerDetector到最尾部
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
		Comparator<Object> comparatorToUse = null;
		if (beanFactory instanceof DefaultListableBeanFactory) {
			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
		}
		if (comparatorToUse == null) {
			comparatorToUse = OrderComparator.INSTANCE;
		}
		postProcessors.sort(comparatorToUse);
	}

	/**
	 * Invoke the given BeanDefinitionRegistryPostProcessor beans.
	 */
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanDefinitionRegistry(registry);
		}
	}

	/**
	 * Invoke the given BeanFactoryPostProcessor beans.
	 */
	private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanFactory(beanFactory);
		}
	}

	/**
	 * Register the given BeanPostProcessor beans.
	 */
	private static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

		for (BeanPostProcessor postProcessor : postProcessors) {
			beanFactory.addBeanPostProcessor(postProcessor);
		}
	}


	/**
	 * BeanPostProcessor that logs an info message when a bean is created during
	 * BeanPostProcessor instantiation, i.e. when a bean is not eligible for
	 * getting processed by all BeanPostProcessors.
	 */
	private static final class BeanPostProcessorChecker implements BeanPostProcessor {

		private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);

		private final ConfigurableListableBeanFactory beanFactory;

		private final int beanPostProcessorTargetCount;

		public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
			this.beanFactory = beanFactory;
			this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
		}

		@Override
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			return bean;
		}

		@Override
		public Object postProcessAfterInitialization(Object bean, String beanName) {
			if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
					this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
				if (logger.isInfoEnabled()) {
					logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
							"] is not eligible for getting processed by all BeanPostProcessors " +
							"(for example: not eligible for auto-proxying)");
				}
			}
			return bean;
		}

		private boolean isInfrastructureBean(@Nullable String beanName) {
			if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
				BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
				return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
			}
			return false;
		}
	}

}
